package com.hyd.issues.auth;

import com.hyd.dao.SimpleTransaction;
import com.hyd.issues.BaseAction;
import com.hyd.issues.DaoUtil;
import com.hyd.issues.json.JsonResult;
import com.hyd.issues.project.Project;
import com.hyd.issues.user.User;
import com.opensymphony.xwork2.ModelDriven;

/**
 * (description)
 *
 * @author yiding.he
 */
public class SetupAction extends BaseAction implements ModelDriven<SetupParameter> {

    private SetupParameter setupParameter = new SetupParameter();

    public JsonResult execute() throws Exception {
        if (User.existsByName(setupParameter.getUsername())) {
            return JsonResult.fail("用户名已存在。");
        }

        new SimpleTransaction() {

            @Override
            protected void execute() throws Exception {
                User.saveUser(setupParameter.getUsername(), setupParameter.getPassword());
                Long adminUserId = DaoUtil.lastInsertId();
                Project.create(setupParameter.getProjectName(), adminUserId);
            }
        }.run();

        return JsonResult.SUCCESS;
    }

    public SetupParameter getModel() {
        return setupParameter;
    }
}
